package org.budo.filestore.ftp;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.budo.filestore.api.DeleteResponse;
import org.budo.filestore.api.DownloadRequest;
import org.budo.filestore.api.UploadRequest;
import org.budo.filestore.api.UploadResponse;
import org.budo.filestore.impl.DefaultDeleteResponse;
import org.budo.filestore.impl.DefaultUploadResponse;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

/**
 * @author lmw
 */
public class FtpFileStore extends AbstractFtpFileStore {
    private static final Logger log = Slf4j.getLogger();

    @Override
    public UploadResponse upload(UploadRequest request) {
        try {
            Boolean success = this.getFtpClient().storeFile(request.getContentUrl(), request.getInputStream());
            return new DefaultUploadResponse(success);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @see #downloadStream(DownloadRequest)
     */
    @Override
    public String downloadUrl(DownloadRequest request) {
        return super.downloadUrl(request);
    }

    @Override
    public InputStream downloadStream(DownloadRequest request) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Boolean success = this.getFtpClient().retrieveFile(request.getContentUrl(), outputStream);
            if (!success) {
                log.error("#46 downloadStream, retrieveFile, fail, request=" + request);
            }

            return new ByteArrayInputStream(outputStream.toByteArray());
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public DeleteResponse delete(DownloadRequest request) {
        try {
            Boolean success = this.getFtpClient().deleteFile(request.getContentUrl());
            return new DefaultDeleteResponse(success);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
}